package com.new_blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.new_blog.common.ResultAjax;
import com.new_blog.common.SessionUtils;
import com.new_blog.mapper.ArticleinfoMapper;
import com.new_blog.model.Articleinfo;
import com.new_blog.model.Userinfo;
import com.new_blog.model.vo.ArticleInfoVo;
import com.new_blog.model.vo.UserInfoVo;
import com.new_blog.service.ArticleinfoService;
import com.new_blog.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TQ02
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/articleinfo")
public class ArticleinfoController {
    @Autowired
    private ArticleinfoService articleService;
    @Autowired
    private UserinfoService userService;
    @Autowired
    private ArticleinfoMapper articleMapper;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;


    //公共列表返回数据
    @RequestMapping("index")
    public ResultAjax index(HttpServletRequest req,int pasize, Integer pindex, int ceo) throws ExecutionException, InterruptedException {
        if(ceo!=0){
            Userinfo user= SessionUtils.getUser(req);
            if(user==null){
                return ResultAjax.fail(-1,"非法进入！");
            }
        }

        FutureTask<List<ArticleInfoVo>> arttask=new FutureTask<>(()->{
            int offest=pasize*(pindex-1);
            return articleService.getAllPage(pasize,offest);
        });
        //返回数据的总数，计算出页数。
        FutureTask<Integer> sizeTask=new FutureTask<>(()->{
            int total =articleService.getCount();
            double sizeTemp=(total * 1.0)/(pasize * 1.0);
            return (int)Math.ceil(sizeTemp); //向上取整
        });
        FutureTask<List<Userinfo>> UserListTask=new FutureTask<>(()->{
            return  userService.getUserAll();
        });

        taskExecutor.submit(arttask);
        taskExecutor.submit(sizeTask);
        taskExecutor.submit(UserListTask);

        List<ArticleInfoVo> art=arttask.get();
        int num=sizeTask.get();
        List<Userinfo> user2= UserListTask.get();


        for(ArticleInfoVo art1:art){
            for(Userinfo user1:user2){
                if(art1.getUid().equals(user1.getUid()))
                {
                    art1.setName(user1.getUname());
                    break;
                }
            }
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("date",art);
        map.put("num",num);
        return ResultAjax.succ(map);
    }

    @RequestMapping("search")
    public ResultAjax search(HttpServletRequest req,int pasize, Integer pindex, String text) throws ExecutionException, InterruptedException {
            Userinfo user= SessionUtils.getUser(req);
            if(user==null){
                return ResultAjax.fail(-1,"非法进入！");
            }
        FutureTask<List<ArticleInfoVo>> arttask=new FutureTask<>(()->{
            int offest=pasize*(pindex-1);
            return articleService.getSearchPage(pasize,offest,text);
        });
        //返回数据的总数，计算出页数。
        FutureTask<String> sizeTask=new FutureTask<>(()->{
            int total =articleService.getSearchCount(text);
            double sizeTemp=(total * 1.0)/(pasize * 1.0);
            String str = total+" "+(int)Math.ceil(sizeTemp);
            return str; //向上取整
        });
        FutureTask<List<Userinfo>> UserListTask=new FutureTask<>(()->{
            return  userService.getUserAll();
        });

        taskExecutor.submit(arttask);
        taskExecutor.submit(sizeTask);
        taskExecutor.submit(UserListTask);

        List<ArticleInfoVo> art=arttask.get();
        String str=sizeTask.get();
        String[] array = str.split(" ");
        int num = Integer.parseInt(array[1]);
        int sum = Integer.parseInt(array[0]);
        List<Userinfo> user2= UserListTask.get();


        for(ArticleInfoVo art1:art){
            for(Userinfo user1:user2){
                if(art1.getUid().equals(user1.getUid()))
                {
                    art1.setName(user1.getUname());
                    break;
                }
            }
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("date",art);
        map.put("num",num);
        map.put("sum",sum);
        return ResultAjax.succ(map);
    }
    //添加文章
    @PostMapping("/add")
    public ResultAjax add(Articleinfo articleInfo, HttpServletRequest req){
        Userinfo userInfo= SessionUtils.getUser(req);
        if(userInfo==null){
            return ResultAjax.fail(-1,"请先登录");
        }
        if(articleInfo==null || !StringUtils.hasLength(articleInfo.getTitle()) ||
                !StringUtils.hasLength(articleInfo.getContent())){
            return ResultAjax.fail(-1,"非法参数");
        }
        Userinfo user=SessionUtils.getUser(req);
        articleInfo.setUid(user.getUid());
        if(articleInfo.getSynopsis().equals("")){
            articleInfo.setSynopsis(articleInfo.getContent().substring(0,30));
        }
        if(articleService.saveOrUpdate(articleInfo)){
            return ResultAjax.succ(1);
        }
        return ResultAjax.fail(-1,"后端出现问题");
    }
    //修改文章
    @RequestMapping("/edit")
    public ResultAjax edit(HttpServletRequest req,Integer aid){
        Userinfo user=SessionUtils.getUser(req);
        if (user == null) {
            return  ResultAjax.fail(-1,"非法访问");
        }
        Articleinfo art=articleMapper.selectOne(new QueryWrapper<Articleinfo>().eq("aId",aid));
        return ResultAjax.succ(art);
    }
    //个人主页
    @RequestMapping("getMylist")
    public ResultAjax getMylist(HttpServletRequest req){
        Userinfo user=SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }
        //存储文章信息
        List<Articleinfo> art=articleMapper.selectList(new QueryWrapper<Articleinfo>().eq("uId",user.getUid()).orderByDesc("aId"));
        //存储人物信息以及数目和类型
        UserInfoVo user2=userService.getUser(user.getUid());
        int num=articleService.getCountId(user2.getUid());
        int type=articleService.getCountType(user2.getUid());
        user2.setCount(num);
        user2.setType(type);

        HashMap<String,Object> map=new HashMap<>();
        map.put("art",art);
        map.put("user",user2);
        return ResultAjax.succ(map);
    }
    //删除文章
    @RequestMapping("/delete")
    public ResultAjax delete(HttpServletRequest req,Integer aid){
        Userinfo user=SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"请先登陆");
        }
        int num=articleService.delete(aid);
        return ResultAjax.succ(num);
    }
    //查看指定文章
    @RequestMapping("getcontent")
    public ResultAjax getlist(HttpServletRequest req,int aId){
        Userinfo user=SessionUtils.getUser(req);
        if(user==null){
            return ResultAjax.fail(-1,"未登陆");
        }
        Articleinfo art=articleService.getId(aId);
        UserInfoVo user2=userService.getUser(art.getUid());
        int num=articleService.getCountId(user2.getUid());
        int type=articleService.getCountType(user2.getUid());
        user2.setCount(num);
        user2.setType(type);
        if(art==null){
            return ResultAjax.fail(-1,"非法查询");
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("art",art);
        map.put("user",user2);
        return ResultAjax.succ(200,map);
    }
    //阅读量自增
    @RequestMapping("/increment")
    public ResultAjax increment(Integer id, HttpServletRequest req){
        Userinfo userInfo=SessionUtils.getUser(req);
        if(userInfo==null){
            return ResultAjax.fail(-1,"请先登录");
        }
        Articleinfo articleinfo=articleMapper.selectOne(new QueryWrapper<Articleinfo>().eq("aid",id));

        if(articleinfo!=null){
            int num=articleinfo.getRcount()+1;
            articleinfo.setRcount(num);
            articleService.saveOrUpdate(articleinfo);
            return ResultAjax.succ("阅读成功");
        }
        return ResultAjax.fail(-1,"失败");
    }

}
